Jupyter에서 실행하기
|
Basic Grammar
1 python CH2. 기본 문법
1.1 수치 할당
import numpy as np
a = 5; b = 6; c = 7
c7
1.2 변수, 논리연산자
# append() : 값 추가
a = [1,2,3]
b=a
a.append(4)
b[1, 2, 3, 4]
1.3 타입 확인
a = 5; b = 'foo'
type(a), type(b)(int, str)
# format() : print{} 안에 내용 추가 (순서대로 0,1,2..)
# float : 소수
a = 4.5; b = 2
print('a is {0}, b is {1}'.format(type(a), type(b)))
a/ba is <class 'float'>, b is <class 'int'>
2.25
# isinstance() : 타입 맞는지 확인
a = 5
isinstance(a, int)True
# 여러 타입 중 하나라도 맞으면 True
a = 5; b = 4.5
isinstance(a, (int, float, str)), isinstance(b, (int, float))(True, True)
1.4 속성, 메서드
a = 'foo'# upper() : 소문자 → 대문자
a.upper()'FOO'
# getattr(객체, 속성) : 객체의 속성에 접근해줌
getattr(a, 'split')<function str.split(sep=None, maxsplit=-1)>
1.5 Duck typing
# 덕 타이핑: "특정 기능을 지원하는가만 중요하다"는 의미를 전달할 때 사용하는 표현
# = 이터러블 객체
def isiterable(obj):
try:
iter(obj)
return True
except TypeError: # 이터러블 하지 않은 값
return Falseisiterable('a string')True
isiterable([1,2,3])True
# 정수는 이터러블 하지 않음
isiterable(5) False
1.6 Import
1.6.0.0.1 some_module.py
1.6.0.0.2 Pi = 3.14159
1.6.0.0.3 def f(x): return x + 2
1.6.0.0.4 def g(a,b):return a+b
# some_module : 임의적으로 만든 py 파일
import some_module
result = some_module.f(5)
result7
pi = some_module.PI
pi3.14159
# 모듈 중 몇개만 import
from some_module import f,g,PI
result = g(5,PI)
result8.14159
# as 로 이름 간략하게 바꿔서도 사용 가능
import some_module as sm
from some_module import PI as pi, g as gf
r1 = sm.f(pi)
r2 = gf(6, pi)
r1, r2(5.14159, 9.14159)
1.7 이항 연산, 비교
5 - 7, 12 + 21.5, 5 <= 2(-2, 33.5, False)
a = [1,2,3]
b = a
c = list(a)
a is b, a is not c(True, True)
a == cTrue
a = None
a is NoneTrue
a_list = ['foo', 2, [4,5]]
a_list[2] = (3,4)
a_list['foo', 2, (3, 4)]
# 잘못된 예시 (수치형을 범주형으로 바꾸려한 경우)
a_tuple = (3, 5, (4,5))
a_tuple[1] = 'four'---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[28], line 3
1 # 잘못된 예시 (수치형을 범주형으로 바꾸려한 경우)
2 a_tuple = (3, 5, (4,5))
----> 3 a_tuple[1] = 'four'
TypeError: 'tuple' object does not support item assignment
ival = 17239871
ival ** 626254519291092456596965462913230729701102721
fval = 7.243
fval2 = 6.78e-5# // : 몫 (% : 나머지)
3/2, type(3/2), 3//2, type(3//2)(1.5, float, 1, int)
a = 'one way of writing a string'
b = 'another way'
a,b('one way of writing a string', 'another way')
# 따옴표 3개 : 여러 줄을 한 줄로 출력
c = '''
This is a longer string that
spans multiple lines
'''
c'\nThis is a longer string that\nspans multiple lines\n'
# 띄어진 줄 개수
c.count('\n')3
# 잘못된 예시 (문자 바꾸려한 경우)
a = 'this is a string'
a[10] = 'f'---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[35], line 3
1 # 잘못된 예시 (문자 바꾸려한 경우)
2 a = 'this is a string'
----> 3 a[10] = 'f'
TypeError: 'str' object does not support item assignment
# replace 이용해 변경
b = a.replace('string', 'longer string')
a,b('this is a string', 'this is a longer string')
# 수치형 → 범주형 변경
a = 5.6
s = str(a)
print(s),
type(s)5.6
str
# list 이용해 문자 하나씩 출력
s = 'python'
list(s)['p', 'y', 't', 'h', 'o', 'n']
# 3전 까지 출력, 3부터 출력
s[:3], s[3:]('pyt', 'hon')
# \n로 줄 띄우기
print('12\n34')12
34
# 이상한 예시
s = '12\\34'
print(s)12\34
# 범주형도 더해진다
a = 'this is the first half'
b = 'and this is the second half'
a + b'this is the first halfand this is the second half'
# {0:.2f} : 소수점 둘째 자리로 반올림
# {1:s} : 두번째 인수의 형식을 범주형으로 저장
# {2:d} : 세번째 인수의 형식을 정확한 정수로 저장
template = '{0:.2f} {1:s} are worth US${2:d}'
template'{0:.2f} {1:s} are worth US${2:d}'
template.format(4.5560, 'Argentine Pesos', 1)'4.56 Argentine Pesos are worth US$1'
template.format(1263.23, 'won', 1)'1263.23 won are worth US$1'
1.8 Booleans
1.8.0.0.1 불리언 타입 - True, False 두가지 값
True and TrueTrue
False or TrueTrue
1.9 Type casting
1.9.0.0.1 원하는 타입으로 해석
s = '3.14159'
fval = float(s)
type(fval)float
int(fval)3
bool(fval)True
# bool : 비어있는 값, 0 → False
bool(0)False
a = None
a is NoneTrue
def add_and_maybe_multiply(a, b, c=None):
result = a + b
if c is not None:
result = result * c
return resultadd_and_maybe_multiply(5,3)8
add_and_maybe_multiply(5,3,10)80
type(None)NoneType
1.10 날짜, 시간 값
from datetime import datetime, date, time
dt = datetime(2011, 10, 29, 20, 30, 21)
dt
# 년, 월, 일, 시, 분, 초datetime.datetime(2011, 10, 29, 20, 30, 21)
dt.day29
dt.minute30
# 년, 월, 일
dt.date()datetime.date(2011, 10, 29)
# 시, 분, 초
dt.time()datetime.time(20, 30, 21)
# strftime : 날짜 문자열을 날짜 객체로 만들 때
dt.strftime('%m/%d/%Y %H:%M'), dt.strftime('%Y/%m/%d %H:%M')('10/29/2011 20:30', '2011/10/29 20:30')
# strptime : 날짜 객체열을 날짜 문자열로 출력 할 때
datetime.strptime('20091031', '%Y%m%d')datetime.datetime(2009, 10, 31, 0, 0)
dt.replace(minute=0, second=0)datetime.datetime(2011, 10, 29, 20, 0)
# 날짜 끼리 연산 가능
dt2 = datetime(2011, 11, 15, 22, 30)
delta = dt2 - dt
deltadatetime.timedelta(days=17, seconds=7179)
type(delta)datetime.timedelta
dt
dt + deltadatetime.datetime(2011, 11, 15, 22, 30)
1.11 Control Flow
x = -5
if x < 0:
print('It is negative')It is negative
x = 8
if x < 0:
print('It is negative')
elif x == 0:
print('Equal to zero')
elif 0 < x < 5:
print('positive but smaller than 5')
else:
print('positive and larger than or equal to 5')positive and larger than or equal to 5
a = 5; b = 7; c = 8; d = 4
if a < b or c > d:
print('Made it')Made it
4>3>2>1, 3>5 or 2>1, 3>5>2>1(True, True, False)
1.12 for loops 루프문
# 잘못된 예시 (+= 는 int, NoneType 지원 안함)
sequence = [1,2,None,4,None,5]
total = 0
for value in sequence:
total += value
# total = total + value---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[72], line 6
3 total = 0
5 for value in sequence:
----> 6 total += value
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'
sequence = [1,2,None,4,None,5]
total = 10
for value in sequence:
if value is None:
continue
total += valuetotal22
sequence = [1,2,0,4,6,5,2,1]
total_until_5 = 0
for value in sequence:
if value == 5:
break
total_until_5 += valuetotal_until_513
list(range(4))[0, 1, 2, 3]
# j가 i 보다 커지기 전까지 조합
for i in range(4):
for j in range(4):
if j > i:
break
print((j,i))(0, 0)
(0, 1)
(1, 1)
(0, 2)
(1, 2)
(2, 2)
(0, 3)
(1, 3)
(2, 3)
(3, 3)
# 전체 조합 출력
for i in range(4):
for j in range(4):
print((i,j))(0, 0)
(0, 1)
(0, 2)
(0, 3)
(1, 0)
(1, 1)
(1, 2)
(1, 3)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(3, 0)
(3, 1)
(3, 2)
(3, 3)
for a, b, c in [[1,2,3],[4,5,6],[7,8,9]]:
print(a,b,c)1 2 3
4 5 6
7 8 9
for a in [[1,2,3],[4,5,6],[7,8,9]]:
print(a)[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
1.13 while loops
x = 256
total = 0
while x > 0:
if total >500:
break
total += x
x = x // 2
print(total,x)
total, x256 128
384 64
448 32
480 16
496 8
504 4
(504, 4)
total,x(504, 4)
1.14 pass
x = 7
if x < 0:
print('negative!')
elif x == 0:
pass
else:
print('positive!')positive!
1.15 range
range(10)range(0, 10)
list(range(10))[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list(range(0, 20, 2))[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
list(range(5, 0, -1))[5, 4, 3, 2, 1]
sum = 0
for i in range(100000):
if i % 3 == 0 or i % 5 == 0:
sum += i
sum2333316668
x = 5
b = 'Non-negative' if x >= 0 else 'Negative'
b'Non-negative'
x = 5
a = 100 if x>=0 else -100
a100
Jupyter에서 실행하기